//
//  MyUploadViewController.m
//  myhuibao
//
//  Created by 孙昕 on 14-2-12.
//  Copyright (c) 2014年 myhuibao. All rights reserved.
//

#import "MyUploadViewController.h"
#import "LoadMoreCell.h"
#import "MyUploadCell.h"
#import "Config.h"
#import "SBJson.h"
#import "OMGToast.h"


@interface MyUploadViewController ()

@end

@implementation MyUploadViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _MainTable.delegate=self;
    _MainTable.dataSource=self;
    pageIndex=1;
    [self GetMyUpload];
    // Do any additional setup after loading the view from its nib.
}

-(void)GetMyUpload
{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?member.memberID=%d&member.password=%@&pageIndex=%d",url_myUpload,[[Config Instance] getMemberId],[[Config Instance] getPassword],pageIndex]] ;
    req = [ASIHTTPRequest requestWithURL:url];
    [req setShouldAttemptPersistentConnection:NO];
    [req setDelegate: self];
    [req setDidFinishSelector:@selector(finishMyUpload:)];
    
    [req startAsynchronous];

}

- (void)finishMyUpload:(ASIHTTPRequest *)request
{
    NSString *jsonStr = [request responseString];
    
    NSDictionary *dic = [jsonStr JSONValue];
    tableDataArray = [dic valueForKey:@"data"];
    if([tableDataArray count]==0)
    {
        [OMGToast showWithText:@"您还没有上传菜品！" bottomOffset:100];
    }
    returnCount=[tableDataArray count];
    [_MainTable reloadData];
    [Config setExtraCellLineHidden:_MainTable];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)OnBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([indexPath row] < ([tableDataArray count])) {
        return 80;
    }else{
        return 40;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	int count = [tableDataArray count];
    if (count>=pageSize) {
        return count+1;
    }else
        return count;
    return count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *CellIdentifier = @"MyUploadIdentifier";
    if([indexPath row] < ([tableDataArray count])) {
        
        MyUploadCell *cell = (MyUploadCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"MyUploadCell" owner:nil options:nil];
            cell = [array objectAtIndex:0];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        
        NSMutableDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
        cell.lbName.text=[item objectForKey:@"name"];
        cell.lbMerchant.text=[item objectForKey:@"merchantName"];
        cell.lbTime.text=[[item objectForKey:@"createTime"] stringByReplacingOccurrencesOfString:@"T" withString:@" "];
        int state=[[item objectForKey:@"hasAudited"] intValue];
        if(state==0)
        {
            cell.lbState.text=@"待审核";
            [cell.lbState setBackgroundColor:[UIColor colorWithRed:210/255.0 green:126/255.0 blue:72/255.0 alpha:1]];
        }
        else if(state==1)
        {
            cell.lbState.text=@"审核通过";
            [cell.lbState setBackgroundColor:[UIColor colorWithRed:253/255.0 green:103/255.0 blue:7/255.0 alpha:1]];
        }
        else
        {
            cell.lbState.text=@"审核未通过";
            [cell.lbState setBackgroundColor:[UIColor colorWithRed:136/255.0 green:136/255.0 blue:136/255.0 alpha:1]];
        }
        if([item objectForKey:@"price"]==[NSNull null])
        {
            cell.lbPrice.text=[NSString stringWithFormat:@"参考价：无"];
        }
        else
        {
            cell.lbPrice.text=[NSString stringWithFormat:@"参考价：%d¥",[[item objectForKey:@"price"] intValue]];
        }
        return cell;
    }else{
        LoadMoreCell *cell = (LoadMoreCell *)[tableView dequeueReusableCellWithIdentifier: @"LoadMoreCellIdentifier"];
        if (cell==nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"LoadMoreCell" owner:nil options:nil];
            cell = [array objectAtIndex:0];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        if(returnCount<pageSize){
            cell.lbText.text=@"";
            cell.hidden = true;
        }else{
            //创建loadMoreCell
            cell.lbText.text=str_more;
        }
        cell.textLabel.textAlignment = UITextAlignmentCenter;
        cell.detailTextLabel.text=@"";
        cell.imageView.image =nil;
        return cell;
        
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (indexPath.row == [tableDataArray count]) {
        LoadMoreCell *loadMoreCell=(LoadMoreCell *)[tableView cellForRowAtIndexPath:indexPath];
        loadMoreCell.lbText.text=str_loading;
        //        [self performSelectorInBackground:@selector(loadMore) withObject:nil];
        //        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?member.memberID=%d&member.password=%@&pageIndex=%d",url_myUpload,[[Config Instance] getMemberId],[[Config Instance] getPassword],++pageIndex]] ;
        req = [ASIHTTPRequest requestWithURL:url];
        [req setDidFinishSelector:@selector(appendTableWith:)];
        [req setShouldAttemptPersistentConnection:NO];
        req.delegate = self;
        [req startAsynchronous];
        return;
    }    //其他cell的事件
    
}
-(void) appendTableWith:(ASIHTTPRequest *)request
{   //将loadMore中的NSMutableArray添加到原来的数据源listData中.
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    NSMutableArray *data = [dic valueForKey:@"data"];
    returnCount=[data count];
    for (int i=0;i<[data count];i++) {
        [tableDataArray addObject:[data objectAtIndex:i]];
    }
    NSMutableArray *insertIndexPaths = [NSMutableArray arrayWithCapacity:pageSize];
    for (int ind = 0; ind < [data count]; ind++) {
        NSIndexPath    *newPath =  [NSIndexPath indexPathForRow:[tableDataArray indexOfObject:[data objectAtIndex:ind]] inSection:0];
        [insertIndexPaths addObject:newPath];
    }
    if ([data count]==0) {
        [_MainTable reloadData];
    }
    //重新调用UITableView的方法, 来生成行.
    [_MainTable insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];
     [Config setExtraCellLineHidden:_MainTable];
}


@end
